/**
 * Created by Anard on 2017/4/19.
 */
var WebSocketServer = require('ws').Server;
var uuid = require('node-uuid');
var clients = require('./clients.js');
var rpc = require('./rpc.js');
var variable = require('../../config/variable.js');

var argv = process.argv.splice(2);
var socketPort = argv[0];
var playerList = {};

rpc.enter();
rpc.match();
rpc.game();

var wss = new WebSocketServer({port: socketPort});
wss.on('connection', function (socket) {
    console.log('connection');
    var id = uuid.v4();
    socket.uuid = id;
    clients[id] = socket;
    socket.on('message', function (message) {
        console.log(message);
        var obj = getMessage(message, socket);
        if (!obj) {
            return false;
        }
        switch (obj.action) {
            case 'reg':
                rpc.send.enterReg(id, null, obj.data);
                break;
            case 'login':
                rpc.send.enterLogin(id, null, obj.data);
                break;
            case 'matchStart':
                rpc.send.matchStart(id, clients[id].userId, obj.data);
                break;
            case 'matchStop':
                rpc.send.matchStop(id, clients[id].userId, obj.data);
                break;
            case 'gameJoin':
                rpc.send.gameJoin(id, clients[id].userId, obj.data);
                break;
            case 'gameExit':
                rpc.send.gameExit(id, clients[id].userId, obj.data);
                break;
            case 'gameReady':
                rpc.send.gameReady(id, clients[id].userId, obj.data);
                break;
            default :
                break;
        }
    });

    // 结束处理
    socket.on('close', function () {
        console.log('close');
        if (socket.uuid) {
            delete clients[socket.uuid];
        }
        socket.close();
    });
    // 错误处理
    socket.on('error', function (e) {
        console.log('close');
        if (socket.uuid) {
            delete clients[socket.uuid];
        }
        socket.close();
    });
});

function getMessage(message, socket) {
    var err = false;
    var obj = null;
    try {
        obj = JSON.parse(message);
    } catch (e) {
        err = true;
    }
    if (typeof (obj) != 'object') {
        err = true;
    }
    if (err) {
        var send = {};
        send.action = 'error';
        send.data = {};
        send.data.code = 1;
        socket.send(JSON.stringify(send));
        return false;
    }
    return obj;
}